<template>
  <div class="laundry-dashboard">
    <!-- 商家信息卡片 -->
    <el-card shadow="hover" class="merchant-info-card">
      <template #header>
        <div class="card-header">
          <div class="merchant-info">
            <el-icon class="merchant-icon"><Shop /></el-icon>
            <div>
              <h3>{{ userStore.merchantName || '洗护商家管理系统' }}</h3>
              <p class="merchant-status">
                <el-tag :type="getStatusType(userStore.merchantStatus)">
                  {{ getStatusText(userStore.merchantStatus) }}
                </el-tag>
                <span class="credit-score">
                  信用分: {{ userStore.businessData.creditScore }}
                  <el-tag size="small" :color="userStore.creditLevel.color">
                    {{ userStore.creditLevel.label }}
                  </el-tag>
                </span>
              </p>
            </div>
          </div>
          <el-button type="primary" @click="refreshData">刷新数据</el-button>
        </div>
      </template>

      <!-- 核心业务指标 -->
      <div class="business-metrics">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="metric-card">
              <div class="metric-icon orders">
                <el-icon><Document /></el-icon>
              </div>
              <div class="metric-content">
                <div class="metric-value">{{ userStore.businessData.totalOrders }}</div>
                <div class="metric-label">总订单数</div>
                <div class="metric-rate">完成率: {{ userStore.businessData.completionRate }}%</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="metric-card">
              <div class="metric-icon revenue">
                <el-icon><Money /></el-icon>
              </div>
              <div class="metric-content">
                <div class="metric-value">¥{{ formatMoney(userStore.businessData.monthlyRevenue) }}</div>
                <div class="metric-label">月收入</div>
                <div class="metric-rate">可提现: ¥{{ formatMoney(userStore.businessData.availableBalance) }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="metric-card">
              <div class="metric-icon reviews">
                <el-icon><Star /></el-icon>
              </div>
              <div class="metric-content">
                <div class="metric-value">{{ userStore.businessData.goodReviewRate }}%</div>
                <div class="metric-label">好评率</div>
                <div class="metric-rate">退款率: {{ userStore.businessData.refundRate }}%</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="metric-card">
              <div class="metric-icon time">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="metric-content">
                <div class="metric-value">{{ userStore.businessData.averageProcessTime }}h</div>
                <div class="metric-label">平均处理时间</div>
                <div class="metric-rate">
                  <el-tag size="small" :type="getTimeType(userStore.businessData.averageProcessTime)">
                    {{ getTimeStatus(userStore.businessData.averageProcessTime) }}
                  </el-tag>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 资金管理 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card shadow="hover" class="finance-card">
          <template #header>
            <div class="card-header">
              <span>资金管理</span>
              <el-button type="success" size="small" @click="handleWithdraw">申请提现</el-button>
            </div>
          </template>
          <div class="finance-content">
            <div class="balance-item">
              <span class="balance-label">可提现余额</span>
              <span class="balance-value available">¥{{ formatMoney(userStore.businessData.availableBalance) }}</span>
            </div>
            <div class="balance-item">
              <span class="balance-label">冻结金额</span>
              <span class="balance-value frozen">¥{{ formatMoney(userStore.businessData.frozenBalance) }}</span>
            </div>
            <div class="balance-item">
              <span class="balance-label">在途金额(14天结算)</span>
              <span class="balance-value pending">¥{{ formatMoney(userStore.businessData.pendingBalance) }}</span>
            </div>
            <el-divider />
            <div class="risk-warning" v-if="userStore.isHighRisk">
              <el-alert
                title="风控提醒"
                type="warning"
                :description="getRiskWarning()"
                show-icon
                :closable="false">
              </el-alert>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="quick-actions-card">
          <template #header>
            <span>快速操作</span>
          </template>
          <div class="quick-actions">
            <el-button type="primary" @click="goToOrders" class="action-btn">
              <el-icon><List /></el-icon>
              订单管理
            </el-button>
            <el-button type="success" @click="goToSettings" class="action-btn">
              <el-icon><Setting /></el-icon>
              接单设置
            </el-button>
            <el-button type="info" @click="goToFinance" class="action-btn">
              <el-icon><Wallet /></el-icon>
              财务中心
            </el-button>
            <el-button type="warning" @click="goToReviews" class="action-btn">
              <el-icon><ChatDotRound /></el-icon>
              评价管理
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 格式化金额
const formatMoney = (amount) => {
  return (amount || 0).toLocaleString()
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'approved': 'success',
    'pending': 'warning',
    'rejected': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'approved': '已认证',
    'pending': '审核中',
    'rejected': '审核未通过'
  }
  return statusMap[status] || '未知状态'
}

// 获取处理时间状态
const getTimeType = (hours) => {
  if (hours <= 12) return 'success'
  if (hours <= 24) return 'warning'
  return 'danger'
}

const getTimeStatus = (hours) => {
  if (hours <= 12) return '快速'
  if (hours <= 24) return '正常'
  return '较慢'
}

// 获取风控警告
const getRiskWarning = () => {
  const warnings = []
  if (userStore.businessData.refundRate > 15) {
    warnings.push(`退款率过高(${userStore.businessData.refundRate}%)`)
  }
  if (userStore.businessData.goodReviewRate < 80) {
    warnings.push(`好评率偏低(${userStore.businessData.goodReviewRate}%)`)
  }
  return warnings.join('，') + '，可能影响提现和搜索排名'
}

// 刷新数据
const refreshData = async () => {
  try {
    await userStore.getMerchantInfo()
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('数据刷新失败')
  }
}

// 申请提现
const handleWithdraw = () => {
  if (userStore.needManualWithdrawReview) {
    ElMessageBox.confirm(
      '由于您的退款率或好评率异常，提现需要人工审核，是否继续？',
      '提现提醒',
      {
        confirmButtonText: '继续申请',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      ElMessage.info('提现申请已提交，请等待人工审核')
    })
  } else {
    ElMessage.success('提现申请已提交，预计1-3个工作日到账')
  }
}

// 快速操作导航
const goToOrders = () => {
  router.push('/main/orders')
}

const goToSettings = () => {
  router.push('/main/settings')
}

const goToFinance = () => {
  router.push('/main/finance')
}

const goToReviews = () => {
  router.push('/main/reviews')
}

// 页面初始化
onMounted(() => {
  console.log('洗护商家仪表板已加载')
  // 初始化商家信息
  userStore.initMerchantInfo()
})
</script>

<style scoped>
.laundry-dashboard {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.merchant-info-card {
  margin-bottom: 20px;
}

.merchant-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.merchant-icon {
  font-size: 32px;
  color: #409EFF;
}

.merchant-info h3 {
  margin: 0;
  color: #1f2937;
  font-size: 18px;
}

.merchant-status {
  margin: 5px 0 0 0;
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
  color: #6b7280;
}

.credit-score {
  display: flex;
  align-items: center;
  gap: 5px;
}

.business-metrics {
  margin-top: 20px;
}

.metric-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #f8fafc;
  border-radius: 8px;
  border-left: 4px solid #409EFF;
}

.metric-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 20px;
  color: white;
}

.metric-icon.orders {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.metric-icon.revenue {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.metric-icon.reviews {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.metric-icon.time {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.metric-content {
  flex: 1;
}

.metric-value {
  font-size: 24px;
  font-weight: bold;
  color: #1f2937;
  margin-bottom: 5px;
}

.metric-label {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 3px;
}

.metric-rate {
  font-size: 12px;
  color: #9ca3af;
}

.finance-card, .quick-actions-card {
  height: 300px;
}

.finance-content {
  padding: 10px 0;
}

.balance-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f3f4f6;
}

.balance-item:last-child {
  border-bottom: none;
}

.balance-label {
  font-size: 14px;
  color: #6b7280;
}

.balance-value {
  font-size: 16px;
  font-weight: bold;
}

.balance-value.available {
  color: #10b981;
}

.balance-value.frozen {
  color: #f59e0b;
}

.balance-value.pending {
  color: #6b7280;
}

.risk-warning {
  margin-top: 15px;
}

.quick-actions {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
  padding: 20px 0;
}

.action-btn {
  height: 60px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.action-btn .el-icon {
  font-size: 20px;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  background: #fafbfc;
  border-bottom: 1px solid #e5e7eb;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-divider) {
  margin: 15px 0;
}
</style>
